package com.yijiupi.plugin.test.progress.impl;

import com.intellij.notification.NotificationGroupManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.progress.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.messages.Topic;
import com.yijiupi.plugin.test.progress.ProgressTestService;
import com.yijiupi.plugin.test.service.TestMoudle;
import org.jetbrains.annotations.NotNull;

/**
 * 后台执行任务
 * 其他线程修改UI
 * 消息总线
 */
public class ProgressTestServiceImpl implements ProgressTestService {
    public static Topic<ProgressTestServiceImpl.TestListenner> TEST_TOPIC=Topic.create("测试主题",TestListenner.class);
    private Project project;
    public ProgressTestServiceImpl(Project project) {
        this.project=project;
    }

    @Override
    public Object testProgressTask() {
        ProgressManager progressManager=ProgressManager.getInstance();
        Object result=null;
        //不可见进度条后台任务
        progressManager.run(new Task.ConditionalModal(project,"测试文本",true, PerformInBackgroundOption.ALWAYS_BACKGROUND) {

            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                try {
                    indicator.setIndeterminate(false);
                    indicator.setText("开始");
                    Thread.sleep(2000);
                    indicator.setFraction(0.4);
                    ApplicationManager.getApplication().invokeLater(()->{
                        ApplicationManager.getApplication().runWriteAction(()->{
                            ServiceManager.getService(TestMoudle.class).setText("修改编辑框");
                        });
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        return result;
    }

    public interface TestListenner{
        void testHandle();
    }
}
